public class Solution200 {
    //上下左右
    int[][] dirs = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};

    public int numIslands(char[][] grid) {
        int count = 0;

        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == '1') {
                    //找到1后开始深度遍历，把周围的值都变成0
                    dfs(grid, i, j);
                    count++;
                }
            }
        }
        return count;
    }

    private void dfs(char[][] grid, int i, int j) {
        grid[i][j] = '0';
        for (int[] dir : dirs) {
            int x = dir[0] + i;
            int y = dir[1] + j;
            //超出边界，或者遇到 0 退出本次循环
            if (x < 0 || x > grid.length || y < 0 || y > grid[0].length || grid[x][y] == '0')
                continue;
            dfs(grid, x, y);
        }
    }
}
